#include "SpaceImp.h"
#include "TraceResult.h"
#include <assert.h>
#include "KdTreeImp.h"

SpaceImp::SpaceImp()
{
	mpResult = new TraceResult;
	mpPartition = NULL;
}

SpaceImp::~SpaceImp()
{
	CleanMembers();
}

void SpaceImp::CleanMembers()
{
	delete mpResult;
	mpResult = NULL;

	delete mpPartition;
	mpPartition = NULL;

	mMeshes.clear();
}

// return number of meshes in the scene
size_t SpaceImp::ClearAllMeshes()
{
	mMeshes.clear();

	return 0;
}

size_t SpaceImp::AddMesh(const TCRTMesh* pMesh)
{
	mMeshes.push_back(const_cast<TCRTMesh*>(pMesh));

	return mMeshes.size();
}

size_t SpaceImp::GetNumberOfMeshes() const
{
	return mMeshes.size();
}

const TCRTMesh* SpaceImp::GetMesh(size_t index) const
{
	if (0 <= index && index < mMeshes.size())
	{
		return mMeshes[index];
	}
	else
	{
		assert(0);
		return NULL;
	}
}

bool SpaceImp::BuildPartition()
{
	mpPartition = new NaiveKdTree(mMeshes);
	return mpPartition->Build();
}

ITraceResult* SpaceImp::TraceRay(RAY* pRay, TraceType traceType)
{
	mpResult->Reset();

	mpPartition->TraceRay(pRay, traceType, mpResult);

	return mpResult;
}